TOPDIR=$(cd "$(dirname "$0")"; pwd)
export PKG_CONFIG_PATH=${TOPDIR}/3rd/lib/pkgconfig

check_cross()
{
    cargo_target=`grep 'target =' .cargo/config.toml |grep -v '#'| awk -F '"' '{print $2}'`
    CROSS=''

    if [ ! -z $cargo_target ] && [[ $cargo_target == aarch64* ]]; then
        CROSS='aarch64-linux-gnu'
    fi

    echo "CROSS=${CROSS}"
}

build_libconf()
{ 
    if [ ! -d 3rd/libconfig ]; then
        git clone https://github.com/hyperrealm/libconfig.git 3rd/libconfig
    fi
     
    cd 3rd/libconfig

    echo "====start build ${TOPDIR}/3rd/libconfig"
    aclocal 
    automake 
    autoconf
    mkdir -p build && cd build
    ../configure -prefix=${TOPDIR}/3rd  --host=$CROSS --disable-cxx --disable-doc
    make
    make install
    cd ../../..
    echo "====DONE build ${TOPDIR}/3rd/libconfig"
}

build_odp()
{
    if [ ! -f ${TOPDIR}/3rd/lib/pkgconfig/libconfig.pc ]; then
        build_libconf
    fi

    echo "====Start build ${TOPDIR}/odp"
    if [ ! -d 3rd/odp ]; then
        git clone https://github.com/OpenDataPlane/odp.git 3rd/odp
    fi
    
    cd 3rd/odp
    autoupdate
    ./bootstrap
    mkdir build
    cd build
    ../configure --prefix=${TOPDIR}/3rd --host=$CROSS --without-openssl
    make
    make install
    cd ../../..
    echo "====DONE build ${TOPDIR}/odp"
}

build_emodp()
{
    if [ ! -f ${TOPDIR}/3rd/lib/pkgconfig/libodp-linux.pc ]; then
        build_odp
    fi

    echo "====start build ${TOPDIR}/em-odp"
    if [ ! -d 3rd/em-odp ]; then
        git clone https://github.com/openeventmachine/em-odp.git 3rd/em-odp
    fi
    
    

    cd 3rd/em-odp 
    if [ -f ../emodp.patch ] && [ ! -f ../patch_done ]; then
        git am ../emodp.patch
        touch ../patch_done
        echo "emodp patch done"
    fi 
    autoupdate
    ./bootstrap
    mkdir build
    cd build
    ../configure --prefix=${TOPDIR}/3rd --host=$CROSS
    make
    make install
    echo "====DONE build ${TOPDIR}/em-odp"
}

if [ ! -f ${TOPDIR}/3rd/lib/pkgconfig/libemodp.pc ]; then
    check_cross
    build_emodp
fi
